import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)
import routes from './routes'

let originPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject)
        return
    }
    originPush.call(this, location, () => {
    }, () => {
    })
}
let router =  new VueRouter({
    routes,
    scrollBehavior() {
        return {x: 0, y: 0}
    }
})
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token
  let name = store.state.user.userInfo.name
  if (token) {
    if (to.path == '/login' || to.path == '/register') {
      next('/home');
    } else {
      // 登录后 进入其他页面刷新时，用户信息丢失
      // 在放行前判断用户信息是否存在，存在则直接放行
      // 不存在则先获取用户信息后，再放行
      if (name) {
        next();
      } else {
        try {
          await store.dispatch('getUserInfo')
          next();
        } catch (error) {
          // token失效 清除token重新登录
          await store.dispatch('userLogout')
          next('/login')
        }
      }
    }
  } else {
    // 未登录 交易、支付、个人中心相关不能进入
    let toPath = to.path;
    if (toPath.indexOf('/trade') != -1 || toPath.indexOf('/pay') != -1 || toPath.indexOf('/center') != -1) {
      // 未登录时跳转路径存储至地址栏路由，登录页获取后，登录成功则跳转该路由
      next('/login?redirect=' + toPath)
    } else {
      next();
    }
  }
})

export default router;